<template>
  <h1>员工列表练习</h1>
  <el-form style="width: 600px;margin: 0 auto;">
    <el-form-item label="姓名">
      <el-input placeholder="请输入员工姓名" v-model="emp.name"/>
    </el-form-item>
    <el-form-item label="工资">
      <el-input placeholder="请输入员工工资" v-model="emp.salary"/>
    </el-form-item>
    <el-form-item label="岗位">
      <el-input placeholder="请输入员工岗位" v-model="emp.job"/>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="addEmp">点我提交</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="arr" style="width: 600px; margin: 0 auto;">
    <el-table-column prop="index" label="编号" width="90" align="center" />
    <el-table-column prop="name" label="姓名" align="center" />
    <el-table-column prop="salary" label="工资" align="center" />
    <el-table-column prop="job" label="岗位" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="danger" @click="del(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import {ref} from "vue";
import {ElMessage} from "element-plus";

const emp = ref({
  name:'',
  salary:'',
  job:''
});
const arr = ref([]);
const addEmp = () => {
  if (emp.value.name.trim() == '' || emp.value.salary.trim() == '' || emp.value.job.trim() == '') {
    ElMessage.error('请输入完整信息');
    return;
  }
  console.log(emp.value);
  // 创建新的对象副本，避免引用问题
  arr.value.push({
    index: arr.value.length + 1,
    name: emp.value.name,
    salary: emp.value.salary,
    job: emp.value.job
  });
  // 清空表单
  emp.value = {
    name:'',
    salary:'',
    job:''
  };
}
const del = (index, emp) => {
  if (confirm("确定要删除" + emp.name + "吗？")) {
    arr.value.splice(index, 1);
    ElMessage.success("删除成功!")
  }
  // 重新编号
  arr.value.forEach((item, index) => {
    item.index = index + 1;
  });
}
</script>

<style scoped>

</style>
